<script>
  import { deepClone } from '@/utils/index'
  import h5esign from '@/components/signature/index.vue'
  import h5cascader from './h5cascader.vue'
  import mobileMap from './mobileMap.vue'  //地图选点组件
  import mobileTree from './mobileTree.vue'
  import {getAccessToken} from '@/utils/auth'
  import {
    getDictData,
    getDataSelect,
    sourceTestList
  } from '@/api/custom/formDesigner'
  function renderMobileDom(h, dataobj) {
    let config = dataobj.__config__;
    let formcopy = this.formConfCopy;
    if (config.tag === 'el-input' && config.tagIcon === 'textarea') {
      return <van-field v-model={this.formDataobj[dataobj.modelValueCur]} required={config.required} label={config.showLabel ? config.label : ''} placeholder={dataobj.placeholder}
        readonly={dataobj.readonly} disabled={dataobj.disabled || formcopy.disabled} type="textarea" maxlength={dataobj.maxlength} rows="2" onBlur={() => { this.submitCheck(dataobj) }} />
    }
    if (config.tag === 'el-number'&& config.tagIcon === 'number') {
      return <van-field v-model={this.formDataobj[dataobj.modelValueCur]} required={config.required} label={config.showLabel ? config.label : ''} placeholder={dataobj.placeholder}
        readonly={dataobj.readonly} disabled={dataobj.disabled || formcopy.disabled} type='digit' onBlur={() => { this.submitCheck(dataobj) }} />
    }
    if (config.tag === 'el-input') {
      return <van-field v-model={this.formDataobj[dataobj.modelValueCur]} required={config.required} label={config.showLabel ? config.label : ''} placeholder={dataobj.placeholder}
        readonly={dataobj.readonly} disabled={dataobj.disabled || formcopy.disabled} type={config.tagIcon === 'password' ? 'password' : 'text'} maxlength={dataobj.maxlength} onBlur={() => { this.submitCheck(dataobj) }} />
    }
    if (config.tag === 'el-input-number') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required}>
        <template slot="input">
          <el-input-number v-model={this.formDataobj[dataobj.modelValueCur]} disabled={dataobj.disabled || formcopy.disabled} step={dataobj.step} min={dataobj.min} max={dataobj.max} onBlur={() => { this.submitCheck(dataobj) }}></el-input-number>
        </template>
      </van-field>
    }
    if (config.tag === 'my-select' && !dataobj.multiple) {
      return <div id="myselectbox">
        <van-field label={config.showLabel ? config.label : ''} required={config.required}>
          <template slot="input">
            <van-dropdown-menu style={{ width: '100%' }}>
              <van-dropdown-item get-container="#myselectbox" v-model={this.formDataobj[dataobj.modelValueCur]} options={dataobj.options} disabled={dataobj.disabled || formcopy.disabled} onChange={() => { this.submitCheck(dataobj) }} />
            </van-dropdown-menu>
          </template>
        </van-field>
      </div>

    }
    if(config.tag === 'my-select' && dataobj.multiple){
      return <van-field label={config.showLabel ? config.label : ''} required={config.required}>
        <template slot="input">
          <el-select v-model={this.formDataobj[dataobj.modelValueCur]} multiple>
        {
          dataobj.options.map((mulinfo)=>{
            return <el-option
      v-for="item in options"
      key={mulinfo.value}
      label={mulinfo.text}
      value={mulinfo.value}>
    </el-option>
          })
        }
    
  </el-select>
        </template>
      </van-field>
    }
    if (config.tag === 'my-radio-group') {

      return <van-field label={config.showLabel ? config.label : ''} required={config.required}>
        <template slot="input">
          <van-radio-group v-model={this.formDataobj[dataobj.modelValueCur]} direction="horizontal" disabled={dataobj.disabled || formcopy.disabled} onChange={() => { this.submitCheck(dataobj) }}>
            {dataobj.options.map(val => <van-radio name={val.value}>{val.label}</van-radio>)}
          </van-radio-group>
        </template>
      </van-field>
    }
    if (config.tag === 'my-checkbox-group') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required}>
        <template slot="input">
          <van-checkbox-group v-model={this.formDataobj[dataobj.modelValueCur]} direction="horizontal" disabled={dataobj.disabled || formcopy.disabled} onChange={() => { this.submitCheck(dataobj) }}>
            {dataobj.options.map(val => <van-checkbox name={val.value}>{val.label}</van-checkbox>)}
          </van-checkbox-group>
        </template>
      </van-field>
    }
    if (config.tag === 'el-switch') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required}>
        <template slot="input">
          <van-switch v-model={this.formDataobj[dataobj.modelValueCur]} disabled={dataobj.disabled || formcopy.disabled} />
        </template>
      </van-field>

    }
    if (config.tag === 'el-slider') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required}>
        <template slot="input">
          <van-slider v-model={this.formDataobj[dataobj.modelValueCur]} disabled={dataobj.disabled || formcopy.disabled} step={dataobj.step} min={dataobj.min} max={dataobj.max} />
        </template>
      </van-field>
    }
    if (config.tag === 'el-rate') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required}>
        <template slot="input">
          <van-rate v-model={this.formDataobj[dataobj.modelValueCur]} disabled={dataobj.disabled || formcopy.disabled} onChange={() => { this.submitCheck(dataobj) }} />
        </template>
      </van-field>
    }
    if (config.tag === 'el-color-picker') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required}>
        <template slot="input">
          <el-color-picker v-model={this.formDataobj[dataobj.modelValueCur]} disabled={dataobj.disabled || formcopy.disabled}></el-color-picker>
        </template>
      </van-field>
    }
    if (config.tag === 'el-time-picker' && config.tagIcon === 'time') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required} onClick={() => { this.getTimeDo(dataobj) }}>
        <template slot="input">
          {this.formDataobj[dataobj.modelValueCur] ? <div class="timeText">{this.formDataobj[dataobj.modelValueCur]}</div> :
            <div style={{ color: '#c8c9cc' }}>选择时间</div>}
        </template>
      </van-field>
    }
    if (config.tag === 'el-time-picker' && config.tagIcon === 'time-range') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required}>
        <template slot="input">
          <div class="timeBox">
            {this.formDataobj[dataobj.modelValueCur][0] ?
              <div class="timeInfo" onClick={() => { this.getTimeDo(dataobj, 0) }}>{this.formDataobj[dataobj.modelValueCur][0]}</div> :
              <div class="timeInfo" style={{ color: '#c8c9cc' }} onClick={() => { this.getTimeDo(dataobj, 0) }}>开始时间</div>}
            <div class="timeTo">-</div>
            {this.formDataobj[dataobj.modelValueCur][1] ?
              <div class="timeInfo" onClick={() => { this.getTimeDo(dataobj, 1) }}>{this.formDataobj[dataobj.modelValueCur][1]}</div> :
              <div class="timeInfo" style={{ color: '#c8c9cc' }} onClick={() => { this.getTimeDo(dataobj, 1) }}>结束时间</div>}
          </div>
        </template>
      </van-field>
    }
    if (config.tag === 'el-date-picker' && config.tagIcon === 'date') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required} onClick={() => { this.getDateDo(dataobj) }} placeholder="选择日期">
        <template slot="input">
          {this.formDataobj[dataobj.modelValueCur] ?
            <div class="timeText">{this.formDataobj[dataobj.modelValueCur]}</div> :
            <div style={{ color: '#c8c9cc' }}>选择日期</div>}
        </template>
      </van-field>
    }
    if (config.tag === 'el-date-picker' && config.tagIcon === 'date-range') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required} onClick={() => { this.getDateDoRange(dataobj) }}>
        <template slot="input">
          {this.formDataobj[dataobj.modelValueCur].length ?
            <div style={{ textAlign: 'left', width: '100%' }}>{this.formDataobj[dataobj.modelValueCur][0]} - {this.formDataobj[dataobj.modelValueCur][1]}</div> :
            <div style={{ color: '#c8c9cc' }}>选择日期范围</div>}
        </template>
      </van-field>
    }
    if (config.tag === 'my-cascader') {
      return <van-field label={config.showLabel ? config.label : ''} required={config.required} onClick={() => { this.getcascader(dataobj) }}>
        <template slot="input">
          <div>{dataobj.cascaderSave}</div>

        </template>
      </van-field>
    }
    if (config.tag === 'el-upload') {

      return <div class="specialMargin">
        <div>{config.required && <span style={{ color: 'red' }}>*</span>}{config.label}</div>
        <el-upload
          action={`${process.env.VUE_APP_BASE_API}/admin-api/infra/file/upload`}
          headers={this.token}
          OnSuccess={(response, file, fileList) => { this.successUpload(response, file, fileList, dataobj.modelValueCur) }}
          show-file-list={false}
          disabled={dataobj.disabled || formcopy.disabled}
          before-upload={(file) => { return this.beforeFileHandler(file, dataobj) }}
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
        <ul class="fileListBox">
          {this.formDataobj[dataobj.modelValueCur].map((fileinfo, index) => {
            return <li>
              {
                ['jpg','jpeg','png'].includes(fileinfo.url.slice(fileinfo.url.lastIndexOf('.')+1).toLowerCase())?<div class="imgmobile" style={{background:'url('+fileinfo.url+')',backgroundSize:'100% 100%'}}>
                  <span class="delmobileimg" onClick={() => { this.deleteFile(dataobj.modelValueCur, index) }}>X</span>
                  </div>:
                <div class="fileinfobox">
                  {fileinfo.name}<span onClick={() => { this.deleteFile(dataobj.modelValueCur, index) }}>删除</span>
                  </div>
              }
            </li>
          })}
        </ul>
      </div>

    }
   if(config.tag === 'tinymce'){
     return <div class="specialMargin">
      <div>{config.required && <span style={{ color: 'red' }}>*</span>}{config.label}</div>
      <tinymce value={this.formDataobj[dataobj.modelValueCur]} onChange={(val) => { this.mobileEdit(dataobj.modelValueCur, val) }}></tinymce>
     </div>
   }
   if(config.tag === 'signature'){
     return <div class="specialMargin">
      <div>{config.required && <span style={{ color: 'red' }}>*</span>}{config.label}</div>
      <h5esign value={this.formDataobj[dataobj.modelValueCur]} esignWidth={350} esignHeight={280} onChange={(val) => { this.esignChange(dataobj.modelValueCur, val) }} disabled={dataobj.disabled || formcopy.disabled}></h5esign>
     </div>
   }
   if(config.tag === 'getMapPoint'){
      return <van-field v-model={this.formDataobj[dataobj.modelValueCur]} required={config.required} label={config.showLabel ? config.label : ''} placeholder={dataobj.placeholder}
        readonly={dataobj.readonly} disabled={dataobj.disabled || formcopy.disabled}  onBlur={() => { this.submitCheck(dataobj) }}>
        <template slot="button">
      <van-button size="small" type="primary" onClick={()=>{this.setMapHandler(dataobj)}} disabled={dataobj.disabled || formcopy.disabled}>选择地点</van-button>
    </template>
        </van-field>
    }
    if(config.tag === 'el-tree-select'){
      return <div class="specialMargin">
        <div>{config.required && <span style={{ color: 'red' }}>*</span>}{config.label}</div>
       <mobile-tree value={this.formDataobj[dataobj.modelValueCur]} options={dataobj.options} defaultValue={config.defaultValue}
       dataType={dataobj.dataType} fields={dataobj.fields} onInput={(val)=>{this.mobileTreeChange(dataobj.modelValueCur,val)}}
       treeDisabled={dataobj.disabled || formcopy.disabled}></mobile-tree>
      </div>
    }
  }
  function renderChildDom(h, dom) {
    // 如果是布局型组件则循环设置
    return dom.map(info => {
      if (info.__config__.children) {
        return renderChildDom.call(this, h, info.__config__.children);
      } else {
        return <div>
          {renderMobileDom.call(this, h, info)}
          <div id={info.modelValueCur} class="requireMesbox"></div>
        </div>
      }
    })
  }
  function renderMobileForm(h, item) {
    // 布局型以及复杂组件在此设置
    let tag = item.__config__.tag;
    if (tag === 'Subform') {
      return <div class="subformbox specialMargin">
        <div class="subformboxinfo">{item.__config__.label}</div>
        {renderChildDom.call(this, h, item.__config__.children)}
      </div>
    } else if (tag === 'el-tabs') {
      return <van-tabs class="specialMargin" style={{ minHeight: '130px' }}>
        {item.__slot__.options.map((dent, index) => {
          return <van-tab title={dent.label} name={dent.name}>{renderChildDom.call(this, h, item.__config__.children[index].__config__.children)}</van-tab>
        })}
      </van-tabs>
    } else if (tag === 'el-collapse') {
      return <van-collapse class="specialMargin" v-model={this.mycollapse}>
        {item.__slot__.options.map((dent, index) => {
          return <van-collapse-item title={dent.title}>{renderChildDom.call(this, h, item.__config__.children[index].__config__.children)}</van-collapse-item>
        })}
      </van-collapse>
    } else if (tag === 'el-card') {
      return <div class="subformbox specialMargin">
        <div class="subformboxinfo">{item.__config__.label}</div>
        {renderChildDom.call(this, h, item.__config__.children)}
      </div>
    }
    else if (tag === 'TitleLine' && item.__config__.tagIcon === 'split') {
      return <div class="splitbox specialMargin" style={{ marginTop: item.styleConfig.marginTop + 'px', marginBottom: item.styleConfig.marginBottom + 'px' }}>
        <div class="splitLine" style={{ borderColor: item.styleConfig.color }}></div>
        <div class="splitText" style={{
          left: item['content-position'] === 'left' ? '10px' : item['content-position'] === 'center' ? '50%' : '70%',
          transform: item['content-position'] === 'center' ? 'translate(-50%,-50%)' : 'translate(0,-50%)'
        }}>{item.content}</div>
      </div>
    } else if (tag === 'TitleLine' && item.__config__.tagIcon === 'title') {
      return <div style={{ fontSize: item.styleConfig.fontSize + 'px', textAlign: item['content-position'], color: item.styleConfig.color }} class="specialMargin">
        <div>{item.content}</div>
      </div>
    } else {
      return <div>
        {renderMobileDom.call(this, h, item)}
        <div id={item.modelValueCur} class="requireMesbox"></div>
      </div>
    }
  }
  function renderPreview(h) {
    // 对于公共的弹框组件在此设置
    return <div id="reviewyidong">
      <van-popup v-model={this.showPopupObj} position="bottom" close-on-click-overlay={true} close-on-popstate={true}>
        <van-datetime-picker onCancel={() => { this.cancelTime() }} onConfirm={(event) => { this.confirmTime(event) }} type="time" />
      </van-popup>
      <van-calendar v-model={this.showDate} min-date={this.minDate} onConfirm={(event) => { this.confirmDate(event) }} />
      <van-calendar v-model={this.showDateRange} type="range" min-date={this.minDate} onConfirm={(event) => { this.confirmDateRange(event) }} />
      <van-popup v-model={this.showh5cascader} position="bottom" close-on-click-overlay={true} close-on-popstate={true} onClose={()=>{this.closeCascader()}}>
        <h5cascader showh5cascader={this.showh5cascader} cascaderobj={this.cascaderobj} onCascaderChange={(selectCur, cur) => { this.cascaderChange(selectCur, cur) }}></h5cascader>
      </van-popup>
      {this.showMap ? <mobile-map onMapInfo={(event)=>{this.setMap(event)}} showMapBox={this.showMap} address={this.mapTextCent} onCloseMobileMap={()=>{this.showMap=false}}></mobile-map>:''}
      {this.formConfCopy.fields.map(item =>
        renderMobileForm.call(this, h, item)
      )}
      {this.status !== 'view' ? <div style={{ display: 'flex', justifyContent: 'center', flexWrap: 'nowrap', marginTop: '10px',marginBottom:'10px' }}>
        {
          Array.isArray(this.formConfCopy.btnConfig) ? this.formConfCopy.btnConfig.filter(item => item.label !== '保存').map((item) => {
            if (item.checked) {
              return <van-button plain type="info" onclick={this[`${item.click}Form`]} size="small" style={{ margin: '0 8px' }}>{item.text}</van-button>
            } else {
              return null
            }
          }) :
            <div style={{ display: 'flex', justifyContent: 'center', flexWrap: 'nowrap' }}>

              <van-button plain type="info" onclick={this.cancelForm} size="small" style={{ margin: '0 8px' }}>取消</van-button>
              <van-button plain type="info" onclick={this.submitForm} size="small" style={{ margin: '0 8px' }}>确认</van-button>
            </div>
        }
      </div> : ''}
    </div>
  }
  export default {
    data() {
      return {
        formConfCopy: {},
        curTimeInfo: '', //暂存时间字段名
        formDataobj: {},
        mycollapse: [],
        showPopupObj: false,
        showDate: false,
        showDateRange: false,
        showh5cascader: false,
        len: 0,
        timeIndex: '',
        curTag: '', //暂存时间类型tag
        minDate: new Date(1997, 1, 1),
        ruleList: [],
        isPass: false, //是否最终通过校验
        cascaderobj: {}, //级联组件需要的数据
        timeObj: null,
        showMap:false,
        mapText:'',
        shouldSetArr:[],
        shouldSetArr2:[],
        shouldSetArr3:[],
        token:{},
        mapTextCent:''
      }
    },
    components: {
      h5esign,
      h5cascader,
      mobileMap,
      mobileTree
    },
    props: {
      formConf: {
        type: Object,
        required: true
      },
      originData: {
        type: Object,
        default: function () {
          return {}
        }
      },
      status: {
        type: String,
        default: 'add'
      },
      tableName: {
        type: String,
        default: ''
      }
    },
    created() {
      this.formConfCopy = deepClone(this.formConf);
      this.setWatchData(this.formConfCopy.fields);
      if (Object.keys(this.originData).length) {
        Object.keys(this.originData).forEach(item => {
          if(this.shouldSetArr.includes(item)){
            let strbn = this.originData[item].split(',').map(s=>{return parseInt(s)})
            this.originData[item] = strbn;
          }
          if(this.shouldSetArr2.includes(item) && !this.originData[item]){
            this.originData[item] = [];
          }
          if(this.shouldSetArr3.includes(item)){
            this.handlerCascader(this.formConfCopy.fields,item);
          }
          for (let val in this.formDataobj) {
            let n = val.lastIndexOf('a');
            let cent = val.slice(0, n);
            if (item === cent) {
              this.formDataobj[val] = this.originData[item]
            }
          }
        })
      }
      this.setChildValueHandle(this.formConfCopy.fields);
    },
    mounted() {
      this.token = {'Authorization':`Bearer ${getAccessToken()}`}
    },
    methods: {
      // 初始化数据
      setWatchData(fields) {
        fields.forEach((item, index) => {
          if(item.__config__.tag==='my-select' && item.multiple){
            this.shouldSetArr.push(item.__vModel__);
          }
          if(item.__config__.tag==='el-upload'){
            this.shouldSetArr2.push(item.__vModel__);
          }
          if(item.__config__.tag==='my-cascader'){
            this.shouldSetArr3.push(item.__vModel__);
          }
          item.modelValueCur = '' + item.__vModel__ + 'a' + index + this.len;
          this.setDefaultHandle(item.__config__);
          if(item.__config__.tag==='el-time-picker'){
            this.formatTime(item);
          }
          this.$set(this.formDataobj, item.modelValueCur, item.__config__.defaultValue);
          this.ruleList.push({
            name: item.modelValueCur,
            rule: item.__config__.regList
          });
          if (Array.isArray(item.__config__.children)) {
            this.len++;
            this.setWatchData(item.__config__.children);
          }
        })
      },
      // 设置不同类型defaultValue
      setDefaultHandle(config) {
        let typearr1 = ['el-input', 'my-radio-group', 'tinymce', 'signature', 'el-tree-select'];
        let typearr2 = ['my-checkbox-group', 'el-upload', 'my-cascader'];
        let typearr3 = ['el-slider','el-rate'];
        let tagval = config.tag;
        let curval = config.defaultValue;
        if (!curval && typearr1.includes(tagval)) {
          config.defaultValue = '';
        } else if ((!curval || !curval.length) && typearr2.includes(tagval)) {
          config.defaultValue = [];
        } else if (!curval && typearr3.includes(tagval)) {
          config.defaultValue = 0;
        } else if(tagval === 'my-select' && config.multiple){
          config.defaultValue = [];
        }else if(tagval === 'my-select' && !config.multiple){
          config.defaultValue = '';
        }else if(tagval === 'el-input-number'){
          config.defaultValue = undefined;
        }else if (config.tag === 'el-time-picker') {
          if (config.tagIcon === 'time' && !curval) {
            config.defaultValue = '';
          } else {
            if (!curval || !curval.length) {
              config.defaultValue = [];
            }
          }
        } else if (config.tag === 'el-date-picker') {
          if (config.tagIcon === 'date' && !curval) {
            config.defaultValue = '';
          } else {
            if (!curval || !curval.length) {
              config.defaultValue = [];
            }
          }
        }
        

      },
      // 设置选择类组件的options
      setValueHandle(item) {
        let val = item.__config__;
        switch (val.tag) {
          case 'my-select':
            this.getSelectData(item);
            break;
          case 'my-radio-group':
            this.getRadioData(item);
            break;
          case 'my-checkbox-group':
            this.getCheckboxData(item);
            break;
        }

      },
      // 循环设置选择类组件的options
      setChildValueHandle(fields){
        fields.forEach(curdef=>{
            this.setValueHandle(curdef);
            if (Array.isArray(curdef.__config__.children)) {
                this.setChildValueHandle(curdef.__config__.children);
            }
        });
      },
      mobileTreeChange(cur,val){
        this.$set(this.formDataobj, cur, val);
        let obj = this.formConfCopy.fields.find(item => {
          return item.modelValueCur === cur;
        });
        this.submitCheck(obj)
      },
      // 级联组件初始化
      getcascader(dataobj) {
        let showTime = dataobj.disabled || this.formConfCopy.disabled;
        if (!showTime) {
          this.cascaderobj = dataobj;
          this.showh5cascader = true;
        }
      },
      // 设置级联组件初始数据
      handlerCascader(arr,item){
        arr.forEach(cent=>{
          if (Array.isArray(cent.__config__.children)) {
            this.handlerCascader(cent.__config__.children,item);
          }else if(cent.__vModel__ === item){
            if(cent.dataType==='dynamic'){
              cent.cascaderSave = cent.__config__.defaultValue.join('/');
            }else{
              let str = '';
              cent.options.forEach(obj=>{
                if(obj.value==this.originData[item][0]){
                  str = obj.label;
                  if(Array.isArray(obj.children) && obj.children.length){
                      obj.children.forEach(child1=>{
                        if(child1.value==this.originData[item][1]){
                      str = str + '/' + child1.label;
                      if(Array.isArray(child1.children) && child1.children.length){
                        child1.children.forEach(child2=>{
                        if(child2.value==this.originData[item][2]){
                      str = str + '/' + child2.label;
                    }
                  })
                }
                    }
                  })
                }
                }
              })
              cent.cascaderSave = str;
            }
          }
        })
      },
      cascaderChange(selectCur, cur) {
        let text = [], valarr = [];
        selectCur.forEach(item => {
          text.push(item.label);
          valarr.push(item.value);
        });
        this.$set(this.formDataobj, cur, valarr);
        let obj = this.formConfCopy.fields.find(item => {
          return item.modelValueCur === cur;
        });
        obj.cascaderSave = text.join('/');
        this.showh5cascader = false;
        this.submitCheck(obj)
      },
      closeCascader(){
        this.showh5cascader = false;
      },
      esignChange(cur, val) {
        this.$set(this.formDataobj, cur, val);
        let obj = this.formConfCopy.fields.find(item => {
          return item.modelValueCur === cur;
        });
        this.submitCheck(obj)
      },
      mobileEdit(cur, val) {
        this.$set(this.formDataobj, cur, val);
        let obj = this.formConfCopy.fields.find(item => {
          return item.modelValueCur === cur;
        });
        this.submitCheck(obj)
      },
      // 点击时间组件弹起弹框，并暂存该组件的tag
      getTimeDo(dataobj, n) {
        let showTime = dataobj.disabled || this.formConfCopy.disabled;
        if (!showTime) {
          this.curTimeInfo = dataobj.modelValueCur;
          this.curTag = dataobj.__config__.tagIcon;
          this.timeIndex = n;
          this.showPopupObj = true;
        }
      },
      // 点击日期组件弹起弹框，并暂存该组件的tag
      getDateDo(dataobj) {
        let showTime = dataobj.disabled || this.formConfCopy.disabled;
        if (!showTime) {
          this.curTimeInfo = dataobj.modelValueCur;
          this.showDate = true;
        }
      },
      getDateDoRange(dataobj) {
        let showTime = dataobj.disabled || this.formConfCopy.disabled;
        if (!showTime) {
          this.curTimeInfo = dataobj.modelValueCur;
          this.showDateRange = true;
        }
      },
      confirmDate(value) {
        let y = value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate();
        this.$set(this.formDataobj, this.curTimeInfo, y);
        this.showDate = false;
      },
      confirmDateRange(value) {
        let y = value[0].getFullYear() + '/' + (value[0].getMonth() + 1) + '/' + value[0].getDate();
        let y1 = value[1].getFullYear() + '/' + (value[1].getMonth() + 1) + '/' + value[1].getDate();
        this.$set(this.formDataobj, this.curTimeInfo, [y, y1]);
        this.showDateRange = false;
      },
      confirmTime(value) {
        if (this.curTag === 'time-range') {
          this.formDataobj[this.curTimeInfo][this.timeIndex] = value;
        } else {
          this.$set(this.formDataobj, this.curTimeInfo, value);
        }
        this.showPopupObj = false;
      },
      setMap(event){
        this.$set(this.formDataobj, this.mapText, event);
        this.showMap = false;
      },
      setMapHandler(dataobj){
        this.showMap = true;
        this.mapText = dataobj.modelValueCur;
        this.mapTextCent = this.formDataobj[this.mapText];
      },
      // 文件上传
      beforeFileHandler(file, dataobj) {

        let fileConfig = dataobj.__config__;
        let str = ''
        let fileArray = [];
        let mesdom = document.getElementById(dataobj.modelValueCur);
        switch (dataobj.accept) {
          case 'image/*':
            fileArray = ['bmp', 'jpg', 'jpeg', 'gif','png'];
            str = '图片';
            break;
          case 'video/*':
            fileArray = ['avi', 'wmv', 'mpg', 'mpeg', 'mov', 'rm', 'ram', 'swf', 'flv', 'mp4'];
            str = '视频';
            break;
          case 'audio/*':
            fileArray = ['mp3', 'mpeg', 'midi', 'wma'];
            str = '音频';
            break;
          case '.xls,.xlsx':
            fileArray = ['xls', 'xlsx'];
            str = 'excel';
            break;
          case '.doc,.docx':
            fileArray = ['doc', 'docx'];
            str = 'doc';
            break;
          case '.pdf':
            fileArray = ['pdf'];
            str = 'pdf';
            break;
          case '.txt':
            fileArray = ['txt'];
            str = 'txt';
            break;
        }
        if (!fileArray.length) {
          mesdom.style.display = 'none';
          return true;
        }

        let n = file.name.lastIndexOf('.') + 1;
        let checkFile = file.name.slice(n).toLowerCase();

        if (!fileArray.includes(checkFile)) {

          this.setErrorMes(mesdom, `请上传${str}格式的文件`);
          return false;
        }
        let size = fileConfig.sizeUnit === 'KB' ? fileConfig.fileSize * 1024 : fileConfig.sizeUnit === 'MB' ? fileConfig.fileSize * 1024 * 1024 : fileConfig.fileSize * 1024 * 1024 * 1024;
        if (file.size > size) {
          this.setErrorMes(mesdom, `文件大小不能超过${fileConfig.fileSize}${fileConfig.sizeUnit}`);
          return false;
        }
        mesdom.style.display = 'none';
        return true;


      },
      successUpload(response, file, fileList, str) {
        console.log(response, file, fileList,'uuuu');
        this.formDataobj[str].push({
          name:file.name,
          url:file.response.data
        });
        console.log(this.formDataobj[str],'filearr');
      },
      deleteFile(str, index) {
        this.formDataobj[str].splice(index, 1);
      },
      cancelTime() {
        this.showPopupObj = false;
      },
      // 校验表单
      submitCheck(item) {
        let arrcheck = ['Subform','TitleLine','el-tabs','Steps','el-collapse','el-card','my-region','el-switch'];
        if(arrcheck.includes(item.__config__.tag)){
         this.isPass = true;
         return;
        }
        if (item.disabled || item.readonly || ('required' in item.__config__ && !item.__config__.required)) {
          this.isPass = true;
        } else if (item.__config__.required) {
          let infoList = this.ruleList.find(val => {
            return val.name === item.modelValueCur
          });
          let infovalue = this.formDataobj[item.modelValueCur];

          let mesdom = document.getElementById(item.modelValueCur);

          if (item.__config__.tag === 'el-time-picker' && item.__config__.tagIcon === 'time-range') {
            if (!infovalue[0]) {
              this.setErrorMes(mesdom, '请选择开始时间');
              return;
            } else if (!infovalue[1]) {
              this.setErrorMes(mesdom, '请选择结束时间');
              return;
            }
          } else if (item.__config__.tag === 'el-date-picker' && item.__config__.tagIcon === 'date-range') {
            if (!infovalue[0]) {
              this.setErrorMes(mesdom, '请选择开始日期');
              return;
            } else if (!infovalue[1]) {
              this.setErrorMes(mesdom, '请选择结束日期');
              return;
            }
          } else if (item.__config__.tag === 'my-checkbox-group') {
            if (!infovalue.length) {
              this.setErrorMes(mesdom, '请选择多选框');
              return;
            }

          } else if (item.__config__.tag === 'my-cascader') {
            if (!infovalue.length) {
              this.setErrorMes(mesdom, '请选择级联选择');
              return;
            }
          } else if (item.__config__.tag === 'el-upload') {
            if (!infovalue.length) {
              this.setErrorMes(mesdom, '请上传文件');
              return;
            }
          }else if(item.__config__.tag === 'el-rate'){
             if (infovalue===0) {
              this.setErrorMes(mesdom, '评分不能为空');
              return;
            }
          } else if(item.__config__.tag === 'my-select' && item.multiple){
            if (!infovalue.length) {
              this.setErrorMes(mesdom, '请选择下拉选择');
              return;
            }
          }
          else if (!infovalue && infovalue !== 0) {

            this.setErrorMes(mesdom, (item.__config__.label + '不能为空'));
            return;
          }
          mesdom.style.display = 'none';
          this.isPass = true;

          if (Array.isArray(infoList.rule) && infoList.rule.length) {
            for (let info of infoList.rule) {
              if (info.pattern && !(new RegExp(eval(info.pattern)).test(infovalue))) {
                this.setErrorMes(mesdom, info.message);
                return;
              } else if (info.validator) {
                let _that = this;
                function callback(err) {
                  try {
                    if (typeof err !== 'undefined') {

                      throw err;
                    } else {
                      mesdom.style.display = 'none';
                      _that.isPass = true;
                    }

                  } catch (e) {

                    _that.setErrorMes(mesdom, e.message);

                  }
                }
                let foo = eval(info.validator);

                foo([], infovalue, callback);

              }
            }

          }

        }


      },
      //重置
      resetForm() {
        this.formConfCopy = deepClone(this.formConf);
        this.curTimeInfo = '';
        this.formDataobj = {};
        this.mycollapse = [];
        this.len = 0;
        this.timeIndex = '';
        this.curTag = '';
        this.ruleList = [];
        this.isPass = false;
        this.cascaderobj = {};
        this.setWatchData(this.formConfCopy.fields);
        if (Object.keys(this.originData).length) {
          Object.keys(this.originData).forEach(item => {
            if(this.shouldSetArr.includes(item)){
            let strbn = this.originData[item].split(',').map(s=>{return parseInt(s)})
            this.originData[item] = strbn;
          }
          if(this.shouldSetArr2.includes(item) && !this.originData[item]){
            this.originData[item] = [];
          }
          if(this.shouldSetArr3.includes(item)){
            this.handlerCascader(this.formConfCopy.fields,item);
          }
            for (let val in this.formDataobj) {
              let n = val.lastIndexOf('a');
              let cent = val.slice(0, n);
              if (item === cent) {
                this.formDataobj[val] = this.originData[item]
              }
            }
          })
        }
        let domobj = document.getElementsByClassName('requireMesbox');
        for (let dom of domobj) {
          dom.style.display = 'none';
        }
        this.$emit('reset')
      },
      //提交
      submitForm() {
        let _that = this;
        let tableValueMap = new Map();
        let subObj = {};
        if (window.location.pathname.indexOf('/formdesign') !== -1) {
          return this.$message.warning('功能预览不支持数据提交')
        }

        function checkValue(arr) {
          for(let item of arr){
            _that.submitCheck(item);
            if (!_that.isPass) {

              return false;
            }
            if (Array.isArray(item.__config__.children)) {

              checkValue(item.__config__.children);
            }
          }
        }
        checkValue(this.formConfCopy.fields);

        if (!_that.isPass) {
          return;
        }
        let fieldNameList = [];
        if (this.isPass) {
          
          this.formConfCopy.fields.forEach(cur => {
            let childarr = [];
            if (cur.__config__.tag === 'Subform') {
              for (let y = 0; y < cur.__config__.children[0].__config__.children.length; y++) {
                let child = cur.__config__.children[0].__config__.children[y]

                fieldNameList.push(child.__vModel__)
              }
              cur.__vModel__ && fieldNameList.push(cur.__vModel__);
              console.log(fieldNameList,'fieldNameList');
              let strmodel = String(cur.__vModel__);
              
                subObj[strmodel] = [];
                cur.__config__.children[0].__config__.children.forEach(val => {
                  let obj = {};
                  for (let strinfo in this.formDataobj) {
                    let n = strinfo.lastIndexOf('a');
                    let cent = strinfo.slice(0, n);

                    if (val.__vModel__ === cent) {
                      obj[val.__vModel__] = this.formDataobj[strinfo]

                    }
                  }
                 
                  subObj[strmodel].push(obj);
                
                });
               
              let objarr = {};
              subObj[String(cur.__vModel__)].forEach(t=>{
                Object.assign(objarr, t);
              })
              childarr.push(objarr);
              tableValueMap.set(cur.__vModel__, childarr)

            }
          })

          
        }
        let objsubmit = {};
        function setValue(arr) {
          arr.forEach((cur) => {
            if (cur.__vModel__) {
              for (let val in _that.formDataobj) {
                let n = val.lastIndexOf('a');
                let cent = val.slice(0, n);

                if (cur.__vModel__ === cent) {
                  objsubmit[cur.__vModel__] = _that.formDataobj[val];
                }
              }
            }
            if (Array.isArray(cur.__config__.children)) {

              setValue(cur.__config__.children);
            }
          })
        }
        setValue(this.formConfCopy.fields);
        fieldNameList.forEach(m=>{
            delete objsubmit[m];
          })
        let params = Object.assign(objsubmit, subObj);
        console.log(params, 'params',tableValueMap);
        this.$emit('submit', params, tableValueMap)
      },
      //保存表单,存到草稿，暂不使用
      saveForm() {

      },
      //取消
      cancelForm() {
        this.$emit('cancel')
      },
      // 校验不通过的组件添加错误提示
      setErrorMes(mesdom, text) {
        mesdom.innerHTML = text;
        mesdom.style.display = 'block';
        this.isPass = false;
      },
      // 格式化时间
      formatTime(itemobj) {
        let n = itemobj.__config__.defaultValue;
        if (itemobj.__config__.tagIcon === 'time-range' && Array.isArray(n) && n.length) {
          let n1 = n[0].split(/\D+/g)[0] + ':' + n[0].split(/\D+/g)[1];
          let n2 = n[1].split(/\D+/g)[0] + ':' + n[1].split(/\D+/g)[1];
          itemobj.__config__.defaultValue = [n1, n2];
        } else if (itemobj.__config__.tagIcon === 'time' && n) {
          itemobj.__config__.defaultValue = n.split(/\D+/g)[0] + ':' + n.split(/\D+/g)[1];
        }
      },
      // 获取下拉数据
      async getSelectData(itemobj) {
        if (itemobj.dataType === 'static') {
          itemobj.options = itemobj.options.map(val => {
            if(this.formDataobj[itemobj.modelValueCur]===val.label || this.formDataobj[itemobj.modelValueCur]===val.value){
              this.formDataobj[itemobj.modelValueCur] = val.value;
            }
            return {
              text: val.label,
              value: val.value
            }
          });

        } else if (itemobj.dataType === 'dictionary') {
          itemobj.options = [];
          if (itemobj.dictName) {
            getDictData({
              dictType: itemobj.dictName
            }).then((res) => {
              if (res.code === 0) {
                res.data.forEach((item) => {
                  itemobj.options.push({
                    text: item.label,
                    value: item.label
                  })
                })
              }
            }).catch(e => {
              console.log(e)
            })
          }
        } else {
            itemobj.options = [];
            if (itemobj.tableName && itemobj.fieldName && itemobj.saveFieldName) {
                const rsp = await sourceTestList(itemobj.tableName)
                if (rsp.code === 0) {
                    itemobj.option = rsp.data?.rowMaps.map((item)=>{
                        return {
                            label:item[itemobj.fieldName],
                            value:item[itemobj.saveFieldName]
                        }
                    })
                    itemobj.options.map(val => {
                        if(this.formDataobj[itemobj.modelValueCur]===val.label || this.formDataobj[itemobj.modelValueCur]===val.value){
                            this.formDataobj[itemobj.modelValueCur] = val.value;
                        }
                    });
                }
            }
            // if (itemobj.tableName !== '' && itemobj.fieldName !== '') {
            //     getDataSelect({
            //         tableName: itemobj.tableName,
            //         column: itemobj.fieldName,
            //     }).then((res) => {
            //         if (res.code === 0) {
            //             res.data.forEach(val=>{
            //                 itemobj.options.push({
            //                     text: val.label,
            //                     value: val.value
            //                 })
            //             })
            //             itemobj.options.map(val => {
            //                 if(this.formDataobj[itemobj.modelValueCur]===val.label || this.formDataobj[itemobj.modelValueCur]===val.value){
            //                     this.formDataobj[itemobj.modelValueCur] = val.value;
            //                 }
            //             });
            //         }
            //     }).catch(e => console.log(e))
            // }
        }
      },
      // 获取单选框组数据
      async getRadioData(itemobj) {
        if (itemobj.dataType === 'static') {
          itemobj.options = itemobj.options;
        } else if (itemobj.dataType === 'dictionary') {
          itemobj.options = []
          if (itemobj.dictName !== '') {
            getDictData({
              dictType: itemobj.dictName
            }).then((res) => {
              if (res.code === 0) {
                res.data.forEach((item) => {
                  itemobj.options.push({
                    label: item.label,
                    value: item.label
                  })
                })
              }
            }).catch(e => {
              console.log(e)
            })
          }
        } else {
            itemobj.options = []
            if (itemobj.tableName && itemobj.fieldName && itemobj.saveFieldName) {
                const rsp = await sourceTestList(itemobj.tableName)
                if (rsp.code === 0) {
                    itemobj.option = rsp.data?.rowMaps.map((item)=>{
                        return {
                            label:item[itemobj.fieldName],
                            value:item[itemobj.saveFieldName]
                        }
                    })
                    itemobj.options.map(val => {
                        if(this.formDataobj[itemobj.modelValueCur]===val.label || this.formDataobj[itemobj.modelValueCur]===val.value){
                            this.formDataobj[itemobj.modelValueCur] = val.value;
                        }
                    });
                }
            }
        }
      },
      //获取多选框组的数据
      async getCheckboxData(itemobj) {
        if (itemobj.dataType === 'static') {
          itemobj.options = itemobj.options;
        } else if (itemobj.dataType === 'dictionary') {
          itemobj.options = []
          if (itemobj.dictName !== '') {
            getDictData({
              dictType: itemobj.dictName
            }).then((res) => {
              if (res.code === 0) {
                res.data.forEach((item) => {
                  itemobj.options.push({
                    label: item.label,
                    value: item.label
                  })
                })
              }
            }).catch(e => {
              console.log(e)
            })
          }
        } else {
            itemobj.options = []
            if (itemobj.tableName && itemobj.fieldName && itemobj.saveFieldName) {
                const rsp = await sourceTestList(itemobj.tableName)
                if (rsp.code === 0) {
                    itemobj.option = rsp.data?.rowMaps.map((item)=>{
                        return {
                            label:item[itemobj.fieldName],
                            value:item[itemobj.saveFieldName]
                        }
                    })
                }
            }
        }
      }
    },
    render(h) {
      return renderPreview.call(this, h)
    }
  }
</script>
<style lang="less">
  .subformbox {
    width: 100%;
    margin: 10px 0;
    border-top: 1px solid #f4f4f4;
    border-bottom: 1px solid #f4f4f4;
    box-shadow: 0px 0px 4px 0px #888888;
    min-height: 130px;

    .subformboxinfo {
      font-weight: bold;
      margin-bottom: 10px;
    }
  }

  .timeText {
    width: 100%;
    text-align: left;
  }

  .timeBox {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;

    .timeTo {
      width: 50px;
    }

    .timeInfo {
      height: 30px;
      flex: 1;
    }
  }

  .splitbox {
    position: relative;
    height: 30px;
    width: 100%;

    .splitLine {
      position: absolute;
      width: 98%;
      border-top: 1px solid black;
      z-index: 1;
      top: 50%;
    }

    .splitText {
      position: absolute;
      z-index: 2;
      height: 30px;
      background: white;
      padding: 0px 8px;
      top: 50%;
      line-height: 30px;
    }
  }

  .fileListBox {
    padding: 0;
    margin-left: 6px;
    list-style: none;

    .fileinfobox {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-top: 5px;
    }
    .imgmobile{
      width:130px;
      height:130px;
      margin:10px;
      background-repeat: no-repeat;
      position: relative;
    }
    .delmobileimg{
      position: absolute;
      top:0;
      right:2px;
      cursor: pointer;
      padding:3px;
    }
  }

  .requireMesbox {
    color: red;
    margin-left: 20px;
    margin-top: 5px;
    font-size: 12px;
  }

  .specialMargin {
    margin: 10px 0;
  }

  .van-switch {
    font-size: 22px;
  }

  .van-dropdown-menu__bar {
    box-shadow: none;
    height: 24px;
  }
  .van-dropdown-menu__item{
    justify-content:left;
  }
  #reviewyidong{
    height: 100%;
  }
  @media only screen and (min-width: 768px) {
    #reviewyidong {
      .van-overlay {
        position: absolute;
      }

      .van-popup {
        position: absolute;
      }
    }

    #myselectbox .van-dropdown-item {
      right: auto !important;
      left: auto !important;
      width: 328px !important;
    }
  }
</style>